package org.dtrd.modules.control.controller;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.dtrd.base.BaseController;
import org.dtrd.common.api.vo.Result;
import org.dtrd.config.system.SystemState;
import org.dtrd.modules.base.service.BaseCommonService;
import org.dtrd.modules.control.entity.bean.PatientTargetValue;
import org.dtrd.modules.control.entity.bean.TargetAndDetailInfo;
import org.dtrd.modules.control.entity.bean.TargetInfo;
import org.dtrd.modules.control.entity.bean.TargetTable;
import org.dtrd.modules.control.entity.po.DtrdEntRdSigninTargetDetail;
import org.dtrd.modules.control.entity.request.TargetPageRequest;
import org.dtrd.modules.control.service.IDtrdEntRdSigninTargetDetailService;
import org.dtrd.modules.control.service.IDtrdEntRdSigninTargetService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import static org.dtrd.common.constant.CommonConstant.*;
import static org.dtrd.config.system.SystemState.ResponseState.STATE_PARAMS_MISSING;

@Api(tags = "控制目标")
@RestController
@RequestMapping("/107/02")
public class ControlTargetController extends BaseController {

    @Autowired
    private IDtrdEntRdSigninTargetService targetService;
    @Autowired
    private IDtrdEntRdSigninTargetDetailService targetDetailService;
    @Autowired
    private BaseCommonService baseCommonService;

    @ApiOperation(value = "查询控制目标列表", response = TargetInfo.class)
    @PostMapping("/1070201")
    public Result<?> getTargetList(@RequestBody TargetPageRequest request) {
        if (isIntParamInvalid(request.getPatientId())) {
            return error(STATE_PARAMS_MISSING);
        }
        handlePageRequest(request);
        IPage<TargetInfo> targets = targetService.pageTarget(request);
        String logContent = String.format("查询控制目标列表，查询用户id：%d", request.getPatientId());
        baseCommonService.addLog(logContent, OPERATE_TYPE_QUERY);
        return Result.OK(targets);
    }

//    @ApiOperation(value = "查询控制目标", notes = "每个患者可以有多条控制目标记录，每条记录有一个当前使用状态，状态为1表示启用，" +
//            "为0表示未启用，状态为1的记录最多只能有一条.查询返回的为状态为1的记录。",response = TargetDetailInfo.class)
//    @GetMapping("/1070202")
//    @AutoLog(value="查询控制目标", operateType = OPERATE_TYPE_QUERY)
//    public Result<?> getTargetDetailByTargetId(@RequestParam("targetId") Integer targetId) {
//        // 校验参数
//        if (isIntParamInvalid(targetId)) {
//            return error(SystemState.ResponseState.STATE_PARAMS_MISSING);
//        }
//        List<DtrdEntRdSigninTargetDetail> details = targetDetailService.list(Wrappers.lambdaQuery(DtrdEntRdSigninTargetDetail.class)
//                .eq(DtrdEntRdSigninTargetDetail::getTargetId, targetId));
//        // 没有 details 记录直接返回
//        if (details == null || details.size() == 0) {
//            return error(SystemState.ResponseState.STATE_NO_RECORD);
//        }
//        List<TargetDetailInfo> detailInfos = details.stream()
//                .map(po -> new TargetDetailInfo().parseFromPo(po))
//                .collect(Collectors.toList());
//        return Result.OK(detailInfos);
//    }

    @ApiOperation(value = "获取控制目标详情", response = TargetAndDetailInfo.class)
    @GetMapping("/1070202")
    public Result<?> getTargetDetailsInfo(@RequestParam Integer targetId){
        if (isIntParamInvalid(targetId)) {
            return error(STATE_PARAMS_MISSING);
        }
        TargetAndDetailInfo info = targetService.getTargetAndDetailsInfo(targetId);
        String logContent = String.format("获取控制目标详情，查询控制目标id：%d", targetId);
        baseCommonService.addLog(logContent, OPERATE_TYPE_QUERY);
        return Result.OK(info);
    }


    @ApiOperation("添加或修改控制目标")
    @PostMapping("/1070203")
    public Result<?> saveOrUpdateTargetAndDetail(@RequestBody @Validated TargetAndDetailInfo request) {
        boolean result = targetService.saveOrUpdateTargetAndDetail(request);
        String logContent = String.format("添加或修改控制目标，编辑用户id：%d", request.getPatientId());
        baseCommonService.addLog(logContent, OPERATE_TYPE_SAVE_OR_UPDATE);
        return result ? Result.OK() : error(SystemState.ResponseState.STATE_OPERATION_FAILURE);
    }

    @ApiOperation("删除控制目标")
    @DeleteMapping("/1070204")
    public Result<?> removeTargetAndDetails(@RequestParam Integer targetId) {
        if (isIntParamInvalid(targetId)) {
            return error(STATE_PARAMS_MISSING);
        }
        targetService.removeById(targetId);
        targetDetailService.remove(Wrappers.lambdaQuery(DtrdEntRdSigninTargetDetail.class)
                .eq(DtrdEntRdSigninTargetDetail::getTargetId, targetId));
        String logContent = String.format("删除控制目标，删除记录id：%d", targetId);
        baseCommonService.addLog(logContent, OPERATE_TYPE_DELETE);
        return Result.OK();
    }

    @ApiOperation(value = "获取患者首页控制目标信息", response = PatientTargetValue.class)
    @GetMapping("/1070205")
    public Result<?> getPatientHomePageInfo(@RequestParam Integer patientId){
        if (isIntParamInvalid(patientId)) {
            return error(STATE_PARAMS_MISSING);
        }
        PatientTargetValue targetValue = targetDetailService.getPatientHomePageInfo(patientId);
        PatientTargetValue patientTargetRealValueThisWeek = targetDetailService.getPatientTargetRealValue(patientId, 1);
        PatientTargetValue patientTargetRealValueLastWeek = targetDetailService.getPatientTargetRealValue(patientId, 2);
        JSONObject result = new JSONObject();
        result.put("target", targetValue);
        result.put("valueThisWeek", patientTargetRealValueThisWeek);
        result.put("valueLastWeek", patientTargetRealValueLastWeek);
        return Result.OK(result);
    }

    @ApiOperation("获取小程序的控制目标表格")
    @GetMapping("/1070206")
    public Result<?> getMiniProgramTargetTable(@RequestParam Integer patientId){
//        TargetTable targetTable = targetDetailService.getPatientTargetTable(patientId);
        TargetTable targetTable = targetDetailService.getPatientTargetTableV2(patientId);
        String logContent = String.format("获取小程序的控制目标表格, %d", patientId);
        baseCommonService.addLog(logContent, OPERATE_TYPE_QUERY);
        return Result.OK(targetTable);
    }

}
